<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 9/5/24
 * Time: 1:57 PM
 */

namespace app\adminapi\logic;


use app\common\logic\BaseLogic;
use app\common\model\app\App;
use app\common\model\skits\Skits;
use app\common\model\skits\SkitsEpisodes;
use app\common\service\douyin\DouyinService;
use think\facade\Log;

class DouyinLogic extends BaseLogic
{
    /**
     * 抖音回调
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function callback($params)
    {
        $type = $params['type'] ?? '';
        $msg  = $params['msg'] ?? '';
        $data = json_decode($msg, true);
        switch ($type) {
            case 'upload_video' :   # 上传视频回调
                Log::write('抖音上传视频回调：' . json_encode($params));
                $open_video_id       = $data['open_video_id'] ?? '';
                $success             = $data['success'] ?? false;
                $success_to_dy_cloud = $data['success_to_dy_cloud'] ?? false;
                if ($success && $success_to_dy_cloud) {
                    $episodes = SkitsEpisodes::where('douyin_media_id', $open_video_id)->findOrEmpty();
                    if (!$episodes->isEmpty() && $episodes->dy_status == 0) {
                        $episodes->dy_status = 1;
                        $episodes->save();
                    }
                }
                break;
            case 'album_audit' :
                Log::write('抖音短剧审核回调：' . json_encode($params));
                $ma_app_id    = $data['ma_app_id'] ?? '';
                $album_id     = $data['album_id'] ?? '';
                $version      = $data['version'] ?? 0;
                $audit_status = $data['audit_status'] ?? 0;
                $audit_msg    = $data['audit_msg'] ?? '';
                $skits        = Skits::where('douyin_drama_id', $album_id)->findOrEmpty();
                if ($skits->isEmpty()) {

                    return false;
                }
                $skits->douyin_version = $version;
                $audit_status == 2 ? $skits->douyin_status = 3 : $skits->douyin_status = 4;
                $skits->douyin_audit_msg = $audit_msg;
                if ($skits->save()) {
                    // 审核成功，自动提交短剧上线版本
                    DouyinService::onlineAlbum($ma_app_id, $album_id, $version);
                }
                break;
            case 'episode_audit' :
                Log::write('抖音剧集审核回调：' . json_encode($params));
                break;
            default:
                return false;
        }

        return true;
    }
}
